import axios from 'axios'
import { ElMessage, ElLoading as Loading } from 'element-plus'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { blobValidate } from '@/utils/ruoyi'
import {isEmpty} from "@/utils/common";
import {getBlobType} from "@/utils/file";

const baseURL = import.meta.env.VITE_APP_BASE_API

export default {
  get(url, name, params, header){
    const downloadLoadingInstance = Loading.service({ text: '正在下载数据，请稍候', spinner: 'Loading', background: 'rgba(0, 0, 0, 0.7)' })
    if(isEmpty(header)){
      header = {}
    }
    header['Authorization'] = 'Bearer ' + getToken()
    axios({
      url: baseURL + url,
      method: 'get',
      params: params,
      responseType: 'blob',
      timeout: 60000*2,
      headers: header,
    }).then(async res => {
      await this.proResponseData(res, name)
    }).finally(()=>{
      downloadLoadingInstance.close()
    })
  },

  post(url, data, name, header){
    const downloadLoadingInstance = Loading.service({ text: '正在下载数据，请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' })
    if(isEmpty(header)){
      header = {}
    }
    header['Authorization'] = 'Bearer ' + getToken()
    axios({
      url: baseURL + url,
      method: 'post',
      responseType: 'blob',
      timeout: 60000*2,
      data: data,
      headers: header,
    }).then(async (res) => {
      await this.proResponseData(res, name)
    }).finally(()=>{
      downloadLoadingInstance.close()
    })
  },

  name(name, isDelete = true) {
    let url = baseURL + "/system/download?resource=" + encodeURIComponent(name) + "&delete=" + isDelete
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then(async (res) => {
      const isBlob = await blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data])
        this.saveAs(blob, decodeURIComponent(res.headers['download-filename']))
      } else {
        await this.printErrMsg(res.data);
      }
    })
  },
  resource(resource) {
    let url = baseURL + "/system/download/resource?resource=" + encodeURIComponent(resource);
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then(async (res) => {
      const isBlob = await blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data])
        this.saveAs(blob, decodeURIComponent(res.headers['download-filename']))
      } else {
        await this.printErrMsg(res.data);
      }
    })
  },
  async resourceStream(resource) {
    const fileType = getBlobType(resource)
    if(isEmpty(fileType)){
      await this.printErrMsg('当前文件不支持预览');
      return
    }

    let url = baseURL + "/system/download/resource?resource=" + encodeURI(resource);
    const {data}= await axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    })

    const isBlob = await blobValidate(data);
    if (isBlob) {
      const blob = new Blob([data],{type:fileType})
      return window.URL.createObjectURL(blob)
    } else {
      await this.printErrMsg(data);
      return ""
    }
  },
  zip(url, name) {
    var url = baseURL + url
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((res) => {
      const isBlob = blobValidate(res.data);
      if (isBlob) {
        const blob = new Blob([res.data], { type: 'application/zip' })
        this.saveAs(blob, name)
      } else {
        this.printErrMsg(res.data);
      }
    })
  },
  saveAs(text, name, opts) {
    saveAs(text, name, opts);
  },
  async printErrMsg(data) {
    const resText = await data.text();
    const rspObj = JSON.parse(resText);
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    ElMessage.error(errMsg);
  },
  async proResponseData(res, name){
    const isBlob = await blobValidate(res.data);
    if (isBlob) {
      const blob = new Blob([res.data])
      let filename = name
      if(isEmpty(filename)){
        filename = res.headers["content-disposition"].replaceAll("attachment;filename=", "")
      }

      if(isEmpty(filename)){
        filename = decodeURI(res.headers['download-filename'])
      }
      this.saveAs(blob, filename)
    } else {
      await this.printErrMsg(res.data);
    }
  },
}

